<template>
  <div class="case-filing-assistance">
    <!-- 测试信息 -->
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
      <strong>测试信息：</strong> 立案辅助页面已成功加载！
    </div>
    
    <div class="container mx-auto px-4 py-6">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-2xl font-bold text-gray-800 mb-2">立案辅助</h1>
        <p class="text-gray-600">高效处理案件立案流程，提升工作效率</p>
      </div>

      <!-- 功能卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <!-- 待立案案件列表 -->
        <div class="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow cursor-pointer" @click="activeTab = 'pending-cases'">
          <div class="p-6">
            <div class="flex items-center justify-between mb-4">
              <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                <i class="fas fa-list-alt text-blue-600 text-xl"></i>
              </div>
              <span class="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full">{{ pendingCasesCount }}</span>
            </div>
            <h3 class="text-lg font-semibold text-gray-800 mb-2">待立案案件列表</h3>
            <p class="text-gray-600 text-sm">查看所有已接收符合立案条件案件(未和解并且未立案)</p>
          </div>
        </div>

        <!-- 生成诉状材料 -->
        <div class="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow cursor-pointer" @click="activeTab = 'generate-documents'">
          <div class="p-6">
            <div class="flex items-center justify-between mb-4">
              <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                <i class="fas fa-file-alt text-green-600 text-xl"></i>
              </div>
              <span class="bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full">自动生成</span>
            </div>
            <h3 class="text-lg font-semibold text-gray-800 mb-2">生成诉状材料</h3>
            <p class="text-gray-600 text-sm">自动根据案件信息、材料信息生成起诉状、证据清单、证据材料,并支持打包下载</p>
          </div>
        </div>

        <!-- 网上立案 -->
        <div class="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow cursor-pointer" @click="activeTab = 'online-filing'">
          <div class="p-6">
            <div class="flex items-center justify-between mb-4">
              <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                <i class="fas fa-globe text-purple-600 text-xl"></i>
              </div>
              <span class="bg-purple-100 text-purple-800 text-xs px-2 py-1 rounded-full">一键立案</span>
            </div>
            <h3 class="text-lg font-semibold text-gray-800 mb-2">网上立案</h3>
            <p class="text-gray-600 text-sm">根据案件信息自动进行一键网上立案</p>
          </div>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="bg-white rounded-lg shadow-md">
        <!-- 标签页导航 -->
        <div class="border-b border-gray-200">
          <nav class="flex space-x-8 px-6">
            <button 
              @click="activeTab = 'pending-cases'"
              :class="[
                'py-4 px-1 border-b-2 font-medium text-sm',
                activeTab === 'pending-cases' 
                  ? 'border-blue-500 text-blue-600' 
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              ]"
            >
              待立案案件列表
              <span class="ml-2 bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full">{{ pendingCasesCount }}</span>
            </button>
            <button 
              @click="activeTab = 'generate-documents'"
              :class="[
                'py-4 px-1 border-b-2 font-medium text-sm',
                activeTab === 'generate-documents' 
                  ? 'border-green-500 text-green-600' 
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              ]"
            >
              生成诉状材料
            </button>
            <button 
              @click="activeTab = 'online-filing'"
              :class="[
                'py-4 px-1 border-b-2 font-medium text-sm',
                activeTab === 'online-filing' 
                  ? 'border-purple-500 text-purple-600' 
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              ]"
            >
              网上立案
            </button>
          </nav>
        </div>

        <!-- 标签页内容 -->
        <div class="p-6">
          <!-- 待立案案件列表 -->
          <div v-if="activeTab === 'pending-cases'" class="pending-cases">
            <div class="flex justify-between items-center mb-6">
              <h2 class="text-xl font-semibold text-gray-800">待立案案件列表</h2>
              <div class="flex gap-3">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索案件..."
                  prefix-icon="el-icon-search"
                  style="width: 250px"
                />
                <el-select v-model="filterStatus" placeholder="状态筛选" style="width: 150px">
                  <el-option label="全部" value="" />
                  <el-option label="待审核" value="pending" />
                  <el-option label="材料齐全" value="ready" />
                  <el-option label="材料不全" value="incomplete" />
                </el-select>
              </div>
            </div>

            <el-table :data="filteredPendingCases" style="width: 100%" v-loading="loading">
              <el-table-column prop="caseNumber" label="案件编号" width="150" />
              <el-table-column prop="caseTitle" label="案件标题" min-width="200" />
              <el-table-column prop="clientName" label="当事人" width="120" />
              <el-table-column prop="caseType" label="案件类型" width="120" />
              <el-table-column prop="receivedDate" label="接收日期" width="120" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="materials" label="材料完整性" width="120">
                <template #default="scope">
                  <el-progress 
                    :percentage="scope.row.materials" 
                    :color="getProgressColor(scope.row.materials)"
                    :show-text="false"
                  />
                  <span class="text-xs text-gray-500">{{ scope.row.materials }}%</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button size="small" type="primary" @click="viewCase(scope.row)">
                    查看详情
                  </el-button>
                  <el-button size="small" type="success" @click="startFiling(scope.row)" :disabled="scope.row.materials < 100">
                    开始立案
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="mt-4 flex justify-between items-center">
              <span class="text-gray-600">共 {{ filteredPendingCases.length }} 条记录</span>
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="filteredPendingCases.length"
                layout="total, sizes, prev, pager, next, jumper"
              />
            </div>
          </div>

          <!-- 生成诉状材料 -->
          <div v-if="activeTab === 'generate-documents'" class="generate-documents">
            <div class="mb-6">
              <h2 class="text-xl font-semibold text-gray-800 mb-4">生成诉状材料</h2>
              <p class="text-gray-600">选择案件，系统将自动生成相关法律文书</p>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <!-- 案件选择 -->
              <div class="bg-gray-50 rounded-lg p-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">选择案件</h3>
                <el-select 
                  v-model="selectedCase" 
                  placeholder="请选择要生成材料的案件"
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="case_ in availableCases"
                    :key="case_.id"
                    :label="`${case_.caseNumber} - ${case_.caseTitle}`"
                    :value="case_.id"
                  />
                </el-select>

                <div v-if="selectedCase" class="mt-4 p-4 bg-white rounded-lg border">
                  <h4 class="font-semibold text-gray-800 mb-2">案件信息</h4>
                  <div class="space-y-2 text-sm">
                    <div class="flex justify-between">
                      <span class="text-gray-600">案件编号：</span>
                      <span class="text-gray-800">{{ getSelectedCaseInfo.caseNumber }}</span>
                    </div>
                    <div class="flex justify-between">
                      <span class="text-gray-600">案件类型：</span>
                      <span class="text-gray-800">{{ getSelectedCaseInfo.caseType }}</span>
                    </div>
                    <div class="flex justify-between">
                      <span class="text-gray-600">当事人：</span>
                      <span class="text-gray-800">{{ getSelectedCaseInfo.clientName }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 材料类型选择 -->
              <div class="bg-gray-50 rounded-lg p-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">选择材料类型</h3>
                <div class="space-y-3">
                  <el-checkbox v-model="documentTypes.complaint" label="起诉状" />
                  <el-checkbox v-model="documentTypes.evidenceList" label="证据清单" />
                  <el-checkbox v-model="documentTypes.evidenceMaterials" label="证据材料" />
                  <el-checkbox v-model="documentTypes.powerOfAttorney" label="授权委托书" />
                  <el-checkbox v-model="documentTypes.identityDocuments" label="身份证明" />
                </div>

                <div class="mt-6">
                  <el-button 
                    type="primary" 
                    size="large" 
                    @click="generateDocuments"
                    :loading="generating"
                    :disabled="!selectedCase || !hasSelectedDocuments"
                    style="width: 100%"
                  >
                    <i class="fas fa-magic mr-2"></i>
                    生成材料
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 生成结果 -->
            <div v-if="generatedDocuments.length > 0" class="mt-8">
              <h3 class="text-lg font-semibold text-gray-800 mb-4">生成结果</h3>
              <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <div 
                  v-for="doc in generatedDocuments" 
                  :key="doc.id"
                  class="bg-white border rounded-lg p-4 hover:shadow-md transition-shadow"
                >
                  <div class="flex items-center justify-between mb-3">
                    <div class="flex items-center">
                      <i :class="getDocumentIcon(doc.type)" class="text-blue-600 mr-2"></i>
                      <span class="font-medium text-gray-800">{{ doc.name }}</span>
                    </div>
                    <el-tag size="small" type="success">已生成</el-tag>
                  </div>
                  <p class="text-sm text-gray-600 mb-3">{{ doc.description }}</p>
                  <div class="flex gap-2">
                    <el-button size="small" type="primary" @click="previewDocument(doc)">
                      预览
                    </el-button>
                    <el-button size="small" type="success" @click="downloadDocument(doc)">
                      下载
                    </el-button>
                  </div>
                </div>
              </div>

              <div class="mt-6 flex justify-center">
                <el-button type="primary" size="large" @click="downloadAll">
                  <i class="fas fa-download mr-2"></i>
                  打包下载全部材料
                </el-button>
              </div>
            </div>
          </div>

          <!-- 网上立案 -->
          <div v-if="activeTab === 'online-filing'" class="online-filing">
            <div class="mb-6">
              <h2 class="text-xl font-semibold text-gray-800 mb-4">网上立案</h2>
              <p class="text-gray-600">选择已生成材料的案件进行一键网上立案</p>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <!-- 立案案件选择 -->
              <div class="bg-gray-50 rounded-lg p-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">选择立案案件</h3>
                <el-select 
                  v-model="filingCase" 
                  placeholder="请选择要立案的案件"
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="case_ in filingReadyCases"
                    :key="case_.id"
                    :label="`${case_.caseNumber} - ${case_.caseTitle}`"
                    :value="case_.id"
                  />
                </el-select>

                <div v-if="filingCase" class="mt-4 p-4 bg-white rounded-lg border">
                  <h4 class="font-semibold text-gray-800 mb-2">立案信息</h4>
                  <div class="space-y-2 text-sm">
                    <div class="flex justify-between">
                      <span class="text-gray-600">管辖法院：</span>
                      <span class="text-gray-800">{{ getFilingCaseInfo.court }}</span>
                    </div>
                    <div class="flex justify-between">
                      <span class="text-gray-600">案件类型：</span>
                      <span class="text-gray-800">{{ getFilingCaseInfo.caseType }}</span>
                    </div>
                    <div class="flex justify-between">
                      <span class="text-gray-600">诉讼标的：</span>
                      <span class="text-gray-800">{{ getFilingCaseInfo.amount }}</span>
                    </div>
                    <div class="flex justify-between">
                      <span class="text-gray-600">材料状态：</span>
                      <el-tag size="small" type="success">材料齐全</el-tag>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 立案配置 -->
              <div class="bg-gray-50 rounded-lg p-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">立案配置</h3>
                <div class="space-y-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">立案方式</label>
                    <el-radio-group v-model="filingMethod">
                      <el-radio label="online">网上立案</el-radio>
                      <el-radio label="offline">现场立案</el-radio>
                    </el-radio-group>
                  </div>

                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">立案时间</label>
                    <el-date-picker
                      v-model="filingDate"
                      type="datetime"
                      placeholder="选择立案时间"
                      style="width: 100%"
                    />
                  </div>

                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">备注信息</label>
                    <el-input
                      v-model="filingNotes"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入立案备注信息"
                    />
                  </div>
                </div>

                <div class="mt-6">
                  <el-button 
                    type="primary" 
                    size="large" 
                    @click="submitFiling"
                    :loading="submitting"
                    :disabled="!filingCase"
                    style="width: 100%"
                  >
                    <i class="fas fa-paper-plane mr-2"></i>
                    提交立案申请
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 立案记录 -->
            <div class="mt-8">
              <h3 class="text-lg font-semibold text-gray-800 mb-4">立案记录</h3>
              <el-table :data="filingRecords" style="width: 100%">
                <el-table-column prop="caseNumber" label="案件编号" width="150" />
                <el-table-column prop="caseTitle" label="案件标题" min-width="200" />
                <el-table-column prop="filingDate" label="立案时间" width="180" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getFilingStatusType(scope.row.status)">
                      {{ getFilingStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="trackingNumber" label="立案号" width="150" />
                <el-table-column label="操作" width="150">
                  <template #default="scope">
                    <el-button size="small" type="primary" @click="viewFilingDetail(scope.row)">
                      查看详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'CaseFilingAssistance',
  setup() {
    const activeTab = ref('pending-cases')
    const loading = ref(false)
    const generating = ref(false)
    const submitting = ref(false)
    
    // 搜索和筛选
    const searchKeyword = ref('')
    const filterStatus = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)

    // 待立案案件数据
    const pendingCases = ref([
      {
        id: 1,
        caseNumber: 'CASE2024001',
        caseTitle: '交通事故人身损害赔偿纠纷',
        clientName: '王先生',
        caseType: '民事纠纷',
        receivedDate: '2024-01-15',
        status: 'ready',
        materials: 100
      },
      {
        id: 2,
        caseNumber: 'CASE2024002',
        caseTitle: '劳动合同纠纷案',
        clientName: '李女士',
        caseType: '劳动争议',
        receivedDate: '2024-01-16',
        status: 'pending',
        materials: 85
      },
      {
        id: 3,
        caseNumber: 'CASE2024003',
        caseTitle: '房屋买卖合同纠纷',
        clientName: '张先生',
        caseType: '合同纠纷',
        receivedDate: '2024-01-17',
        status: 'incomplete',
        materials: 60
      }
    ])

    // 生成材料相关
    const selectedCase = ref('')
    const documentTypes = ref({
      complaint: true,
      evidenceList: true,
      evidenceMaterials: false,
      powerOfAttorney: true,
      identityDocuments: true
    })
    const generatedDocuments = ref([])

    // 网上立案相关
    const filingCase = ref('')
    const filingMethod = ref('online')
    const filingDate = ref('')
    const filingNotes = ref('')
    const filingRecords = ref([
      {
        id: 1,
        caseNumber: 'CASE2024001',
        caseTitle: '交通事故人身损害赔偿纠纷',
        filingDate: '2024-01-18 10:30:00',
        status: 'success',
        trackingNumber: 'LA2024001001'
      }
    ])

    // 计算属性
    const pendingCasesCount = computed(() => pendingCases.value.length)

    const filteredPendingCases = computed(() => {
      let filtered = pendingCases.value

      if (searchKeyword.value) {
        filtered = filtered.filter(case_ => 
          case_.caseNumber.includes(searchKeyword.value) ||
          case_.caseTitle.includes(searchKeyword.value) ||
          case_.clientName.includes(searchKeyword.value)
        )
      }

      if (filterStatus.value) {
        filtered = filtered.filter(case_ => case_.status === filterStatus.value)
      }

      return filtered
    })

    const availableCases = computed(() => 
      pendingCases.value.filter(case_ => case_.materials >= 80)
    )

    const getSelectedCaseInfo = computed(() => {
      const case_ = pendingCases.value.find(c => c.id === selectedCase.value)
      return case_ || {}
    })

    const hasSelectedDocuments = computed(() => {
      return Object.values(documentTypes.value).some(type => type)
    })

    const filingReadyCases = computed(() => 
      pendingCases.value.filter(case_ => case_.materials === 100)
    )

    const getFilingCaseInfo = computed(() => {
      const case_ = pendingCases.value.find(c => c.id === filingCase.value)
      return {
        ...case_,
        court: '北京市朝阳区人民法院',
        amount: '50,000元'
      }
    })

    // 方法
    const getStatusType = (status) => {
      const types = {
        pending: 'warning',
        ready: 'success',
        incomplete: 'danger'
      }
      return types[status] || 'info'
    }

    const getStatusText = (status) => {
      const texts = {
        pending: '待审核',
        ready: '材料齐全',
        incomplete: '材料不全'
      }
      return texts[status] || '未知'
    }

    const getProgressColor = (percentage) => {
      if (percentage >= 100) return '#67C23A'
      if (percentage >= 80) return '#E6A23C'
      return '#F56C6C'
    }

    const viewCase = (case_) => {
      ElMessage.info(`查看案件详情：${case_.caseTitle}`)
    }

    const startFiling = (case_) => {
      ElMessage.success(`开始立案流程：${case_.caseTitle}`)
      activeTab.value = 'generate-documents'
      selectedCase.value = case_.id
    }

    const getDocumentIcon = (type) => {
      const icons = {
        complaint: 'fas fa-file-alt',
        evidenceList: 'fas fa-list',
        evidenceMaterials: 'fas fa-folder',
        powerOfAttorney: 'fas fa-user-tie',
        identityDocuments: 'fas fa-id-card'
      }
      return icons[type] || 'fas fa-file'
    }

    const generateDocuments = async () => {
      generating.value = true
      
      try {
        // 模拟生成过程
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        const documents = []
        if (documentTypes.value.complaint) {
          documents.push({
            id: 1,
            type: 'complaint',
            name: '民事起诉状',
            description: '根据案件信息自动生成的起诉状'
          })
        }
        if (documentTypes.value.evidenceList) {
          documents.push({
            id: 2,
            type: 'evidenceList',
            name: '证据清单',
            description: '整理的所有证据材料清单'
          })
        }
        if (documentTypes.value.powerOfAttorney) {
          documents.push({
            id: 3,
            type: 'powerOfAttorney',
            name: '授权委托书',
            description: '当事人授权律师代理的委托书'
          })
        }
        if (documentTypes.value.identityDocuments) {
          documents.push({
            id: 4,
            type: 'identityDocuments',
            name: '身份证明',
            description: '当事人身份证明材料'
          })
        }

        generatedDocuments.value = documents
        ElMessage.success('材料生成成功！')
      } catch (error) {
        ElMessage.error('材料生成失败，请重试')
      } finally {
        generating.value = false
      }
    }

    const previewDocument = (doc) => {
      ElMessage.info(`预览文档：${doc.name}`)
    }

    const downloadDocument = (doc) => {
      ElMessage.success(`下载文档：${doc.name}`)
    }

    const downloadAll = () => {
      ElMessage.success('打包下载所有材料')
    }

    const getFilingStatusType = (status) => {
      const types = {
        success: 'success',
        pending: 'warning',
        failed: 'danger'
      }
      return types[status] || 'info'
    }

    const getFilingStatusText = (status) => {
      const texts = {
        success: '立案成功',
        pending: '处理中',
        failed: '立案失败'
      }
      return texts[status] || '未知'
    }

    const submitFiling = async () => {
      submitting.value = true
      
      try {
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        const newRecord = {
          id: filingRecords.value.length + 1,
          caseNumber: getFilingCaseInfo.value.caseNumber,
          caseTitle: getFilingCaseInfo.value.caseTitle,
          filingDate: filingDate.value || new Date().toLocaleString(),
          status: 'success',
          trackingNumber: `LA${Date.now()}`
        }
        
        filingRecords.value.unshift(newRecord)
        ElMessage.success('立案申请提交成功！')
        
        // 重置表单
        filingCase.value = ''
        filingDate.value = ''
        filingNotes.value = ''
      } catch (error) {
        ElMessage.error('立案申请提交失败，请重试')
      } finally {
        submitting.value = false
      }
    }

    const viewFilingDetail = (record) => {
      ElMessage.info(`查看立案详情：${record.caseTitle}`)
    }

    onMounted(() => {
      // 初始化数据
    })

    return {
      activeTab,
      loading,
      generating,
      submitting,
      searchKeyword,
      filterStatus,
      currentPage,
      pageSize,
      pendingCases,
      selectedCase,
      documentTypes,
      generatedDocuments,
      filingCase,
      filingMethod,
      filingDate,
      filingNotes,
      filingRecords,
      pendingCasesCount,
      filteredPendingCases,
      availableCases,
      getSelectedCaseInfo,
      hasSelectedDocuments,
      filingReadyCases,
      getFilingCaseInfo,
      getStatusType,
      getStatusText,
      getProgressColor,
      viewCase,
      startFiling,
      getDocumentIcon,
      generateDocuments,
      previewDocument,
      downloadDocument,
      downloadAll,
      getFilingStatusType,
      getFilingStatusText,
      submitFiling,
      viewFilingDetail
    }
  }
}
</script>

<style scoped>
.case-filing-assistance {
  min-height: 100vh;
  background: #f5f7fa;
}

/* 自定义样式 */
.el-progress {
  margin-right: 8px;
}

.el-table .el-table__row:hover {
  background-color: #f5f7fa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .grid {
    grid-template-columns: 1fr;
  }
  
  .el-table {
    font-size: 12px;
  }
}
</style>
